math.js ➔ quantile   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 12
rs 10
c 0
b 0
f 0
cc 3
1
/**
2
 * Calculates sum of an array
3
 * @param {array} arr array of numbers
4
 * @returns {number} sum of numbers
5
 */
6
export function sum(arr) {
7
    return arr.reduce((a, b) => a + b, 0);
8
}
9
10
/**
11
 * Calculates mean of an array
12
 * @param {array} arr array of numbers
13
 * @returns {number} mean
14
 */
15
export function mean(arr) {
16
    return sum(arr) / arr.length;
17
}
18
19
/**
20
 * Calculates standart deviation
21
 * @param {array} arr array of numbers
22
 * @returns {number} standart deviation
23
 */
24
export function std(arr) {
25
    const mu = mean(arr);
0 ignored issues
show
Unused Code introduced by
The constant mu seems to be never used. Consider removing it.
Loading history...
26
    const diffArr = arr.map(a => (a - mu) ** 2);
0 ignored issues
show
Unused Code introduced by
The parameter a is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
27
28
    return Math.sqrt(sum(diffArr) / arr.length);
29
}
30
31
/**
32
 * Calculates quantiles
33
 * @param {array} arr array of numbers
34
 * @param {number} q quantile (0.25)
35
 * @returns {number}
36
 */
37
export function quantile(arr, q) {
38
    const sorted = arr.sort((a, b) => a - b);
39
    const pos = (sorted.length - 1) * q;
40
    const base = Math.floor(pos);
41
    const rest = pos - base;
42
43
    if (sorted[base + 1] !== undefined) {
44
        return sorted[base] + rest * (sorted[base + 1] - sorted[base]);
45
    }
46
47
    return sorted[base];
48
}
49
50